import { asyncRoutes, resetRouter } from '../router'

// 将菜单信息转成对应的路由信息 动态添加
export function menusToRoutes (data) {
  const result = []
  const children = []

  result.push({
    path: '/',
    component: () => import('@/pages/BaseFramework'),
    children
  })

  data.forEach(item => {
    generateRoutes(children, item)
  })
  children.push({
    path: '/menuConfig',
    name: 'menuConfig',
    component: () => import('@/pages/menuItem/menuConfig')
  })
  children.push({
    path: '/goodDetail',
    name: 'goodDetail',
    component: () => import('@/pages/menuItem/goods-list/com/goodDetail')
  })
  children.push({
    path: '/goodEdit',
    name: 'goodEdit',
    component: () => import('@/pages/menuItem/goods-list/com/edit')
  })
  children.push({
    path: '/codeDetail',
    name: 'codeDetail',
    component: () => import('pages/menuItem/code-detail/')
  })
  children.push({
    path: '/welcome',
    name: 'WelCome',
    component: () => import('@/pages/menuItem/welcome/WelCome')
  })
  children.push({
    path: '404',
    name: 'P404',
    component: () => import('common/Page404')
  })

  // 最后添加404页面 否则会在登陆成功后跳到404页面
  result.push(
    {path: '*', redirect: '/404'}
  )
  return result
}

function generateRoutes (children, item) {
  if (item.name) {
    children.push(asyncRoutes[item.name])
  } else if (item.children) {
    item.children.forEach(e => {
      generateRoutes(children, e)
    })
  }
}

export function resetTokenAndClearUser () {
  // 退出登陆 清除用户资料
  localStorage.removeItem('ycd_token')
  localStorage.removeItem('ycd_username')
  localStorage.removeItem('menuItems')
  // 重设路由
  resetRouter()
}
